// 富文本编辑器
import React, { useState, useEffect } from 'react'
import { useNavigate } from "react-router-dom";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import conBack from '../../style/contentBack/contentBack.module.less'
import { htAffiche, htAfficheUpdate } from '../../apis/policyInformation'
import { Timeline, Button, Image, Pagination, message, FloatButton, Modal } from 'antd';
import { CloseCircleOutlined, ExclamationOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
export default function MyEditor(props) {
  const navigate = useNavigate()
  const { html, setHtml, dataItem, keyWords } = props
  // editor 实例
  const [editor, setEditor] = useState(null)
  const [text, setText] = useState('')
  const [messageApi, contextHolder] = message.useMessage();
  const key = 'updatable';
  const [modal, contextHolder_] = Modal.useModal();
  // 工具栏配置
  const toolbarConfig = {

  }
  // 初始化默认配置
  const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {}
  }
  editorConfig.MENU_CONF['uploadImage'] = {
    server: `https://iotcloud.sc-iot.cn:22002/upload?folder=editor&access_token=${localStorage.getItem('token')}`,
    fieldName: 'file',
    headers: {
      Authorization: 'Bearer ' + localStorage.getItem('token'),
    },
    success: (res) => {
      console.log('res', res)
    },
    // 上传之前触发
    onBeforeUpload(file) { // TS 语法
      // onBeforeUpload(file) {    // JS 语法
      // file 选中的文件，格式如 { key: file }
      return file
      // 可以 return
      // 1. return file 或者 new 一个 file ，接下来将上传
      // 2. return false ，不上传这个 file
    },
    // 上传进度的回调函数
    onProgress(progress) {  // TS 语法
      // onProgress(progress) {       // JS 语法
      // progress 是 0-100 的数字
      console.log('progress', progress)
    },
    // 自定义插入图片
    customInsert(res, insertFn) {  // TS 语法
      // customInsert(res, insertFn) {                  // JS 语法
      // res 即服务端的返回结果
      let { url } = res
      // 从 res 中找到 url alt href ，然后插入图片
      insertFn(url)
    },
  }

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])
  // const addArticle = () => {
  //   console.log('新增')
  //   setShowBox(!showBox)
  // }



  // const addArticleContentAll = () => {
  //   const text = editor.getText()
  //   console.log(text)
  // }
  //修改文章
  const htAfficheUpdata = async () => {
    messageApi.open({
      key,
      type: 'loading',
      content: '修改中...',
    });
    const { data } = await htAfficheUpdate({ ...dataItem, info: html, name: keyWords })

    if (data.state === 1) {
      messageApi.open({
        key,
        type: 'success',
        content: '修改成功!',
        duration: 2,
      });
      window.history.back();
    } else {
      messageApi.open({
        key,
        type: 'error',
        content: data.msg,
        duration: 2,
      });
    }

  }
  const confirm = () => {
    window.history.back();
    // navigate('/operatingDemonstration');
  };
  const updataAirt = () => {
    modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined />,
      content: '确定要修改文章吗？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        htAfficheUpdata()
      },
      onCancel() {
      }
    });
  }
  return (
    <>
      <div style={{ border: '1px solid #ccc', zIndex: 1 }}>
        {contextHolder}
        {contextHolder_}
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={editor => setHtml(editor.getHtml())}
          mode="default"
          style={{ height: '70vh', overflowY: 'hidden', width: '90vw' }}
        />
      </div>
      <FloatButton
        icon={< CloseCircleOutlined />}
        type="primary"
        description="取消"
        onClick={() => confirm()}
        style={{
          right: 94,
        }}
      />
      <FloatButton
        icon={<ExclamationOutlined />}
        type="primary"
        description="确认修改"
        onClick={() => updataAirt()}
        style={{
          right: 24,
        }}
      />
    </>
  )
}

